package com.share.PACManager.task;

import java.net.URLEncoder;
import java.util.Map;
import java.util.TreeMap;
import org.json.JSONException;
import org.json.JSONObject;

import com.share.PACManager.model.CompanyPersonModel;
import com.share.PACManager.model.FreePersonModel;
import com.share.PACManager.model.LeasePersonModel;
import com.share.PACManager.model.PersonModel;
import com.share.PACManager.model.TerminalModel;
import com.share.PACManager.net.HTTPResponse;
import com.share.PACManager.net.HttpUtility;
import com.share.PACManager.utils.Cryptography;
import com.share.PACManager.utils.Utils;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

public class AddPersonTask extends Thread{

	private AddPersonListener mListener;
	private Context mContext;	
	private TerminalModel mTerminal;
	private PersonModel mPerson;
	private String mMessage;
	
	public interface AddPersonListener {
		public TerminalModel requestTerminal();
		public PersonModel requestPerson();
		public void onCheckResult(boolean result, PersonModel person, String message);
	}

	public AddPersonTask(Context context) {
		mContext = context;
	}
	
	public void start(AddPersonListener listener) {
		mListener = listener;
		if(mListener != null)
		{
			mTerminal = mListener.requestTerminal();
			mPerson = mListener.requestPerson();
			start();
		}
	}
	
	private Handler handler = new Handler(){		
		@Override
		public void handleMessage(Message msg)
		{
			if(mListener != null)
			{
				if(msg.what != 0)
					mListener.onCheckResult(false, mPerson,mMessage);
				else
				{
					HTTPResponse resp = (HTTPResponse) msg.obj;
					if(!parse(resp.content))
						mListener.onCheckResult(false, mPerson,mMessage);
					else
					{
						mListener.onCheckResult(true, mPerson,mMessage);
					}
				}
			}				
		}
	};
	
    public boolean parse(String json)
    {
		try {
			JSONObject jsonObject = new JSONObject(json);
			mMessage = jsonObject.getString("Message");
			if(!jsonObject.getBoolean("Success"))
				return false;
			
			return true;
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return false;
    }
    
	@Override
	public void run() {	

		try {
			String terminalId = mTerminal.TerminalId;
			String imei = mTerminal.TerminalCode;
			String password = mTerminal.TerminalPassword;
			String ticket = Cryptography.AES_Encode(imei, terminalId, password);

			String info =	"PersonId=" + Utils.URLEncode(mPerson.PersonId) + "&" +
				"PersonCompanyId=" + Utils.URLEncode(mPerson.PersonCompanyId) + "&" +
				"PersonCompanyType=" + Utils.URLEncode(mPerson.PersonCompanyType) + "&" +
				"PersonPoliceId=" + Utils.URLEncode(mPerson.PersonPoliceId) + "&" +
				"PersonTerminalId=" + Utils.URLEncode(mPerson.PersonTerminalId) + "&" +
				"PersonTransactionId=" + Utils.URLEncode(mPerson.PersonTransactionId) + "&" +
				"PersonCardType=" + Utils.URLEncode(mPerson.PersonCardType) + "&" +
				"PersonCardId=" + Utils.URLEncode(mPerson.PersonCardId) + "&" +
				"PersonName=" + Utils.URLEncode(mPerson.PersonName) + "&" +
				"PersonSex=" + Utils.URLEncode(mPerson.PersonSex) + "&" +
				"PersonNation=" + Utils.URLEncode(mPerson.PersonNation )+ "&" +
				"PersonNative=" + Utils.URLEncode(mPerson.PersonNative) + "&" +
				"PersonBirthday=" + Utils.URLEncode(mPerson.PersonBirthday) + "&" +
				"PersonAddress=" + Utils.URLEncode(mPerson.PersonAddress) + "&" +
				"PersonPhoneNumber=" + Utils.URLEncode(mPerson.PersonPhoneNumber) + "&" +
				"PersonEastPoint=" + Utils.URLEncode(mPerson.PersonEastPoint) + "&" +
				"PersonNorthPoint=" + Utils.URLEncode(mPerson.PersonNorthPoint) + "&" +
				//"PersonCardImage=" + Utils.URLEncode(mPerson.PersonCardImage) + "&" +
				//"PersonRealImage=" + Utils.URLEncode(mPerson.PersonRealImage) + "&" +
				"PersonComment=" + Utils.URLEncode(mPerson.PersonComment) + "&" +
				"PersonStatus=" + Utils.URLEncode(mPerson.PersonStatus);
			
			if(!Utils.isEmptyString(mPerson.PersonCardImage))
				info += "&PersonCardImage=" +  Utils.URLEncodeImage(mPerson.PersonCardImage);
			
			if(!Utils.isEmptyString(mPerson.PersonRealImage))
				info += "&PersonRealImage=" +  Utils.URLEncodeImage(mPerson.PersonRealImage);
			
			if(mPerson instanceof CompanyPersonModel)
			{
				CompanyPersonModel person = (CompanyPersonModel) mPerson;
				info += "&CheckInTime=" + person.CheckInTime + "&" +
						"CheckOutTime=" + person.CheckOutTime + "&" +
						"Office=" + person.Office + "&" +
						"Job=" + person.Job;
			}
			else if(mPerson instanceof LeasePersonModel)
			{
				LeasePersonModel person = (LeasePersonModel) mPerson;
				info += "&CheckInTime=" + person.CheckInTime + "&" +
						"LeaseReason=" + person.LeaseReason + "&" +
						"CheckOutTime=" + person.CheckOutTime;
			}
			else if(mPerson instanceof FreePersonModel)
			{
				FreePersonModel person = (FreePersonModel) mPerson;
				info += "&CheckInTime=" + person.CheckReason;
			}
			info = Cryptography.AES_Encode(info, terminalId, password);

			Map<String, String> params = new TreeMap<String, String>();
			params.put("Id", terminalId);
			params.put("TerminalId", terminalId);
			params.put("DataType", "Data");	
			params.put("Password", password);
			params.put("TerminalCode", imei);
			params.put("Version", "1.0");
			params.put("Ticket", ticket);
			params.put("Objective", "AddPerson");
			
			String entity = "Information=" + URLEncoder.encode(info);			
			handler.obtainMessage(0, HttpUtility.httpPost(params, entity)).sendToTarget();

		} catch (Exception e) {
			handler.obtainMessage(1).sendToTarget();
		}
		
		super.run();
	}	
	
	
}
